<?php

namespace app\services;

use app\traits\Page;
use plugin\admin\app\model\User;
use plugin\admin\app\model\UserFollowing;
use plugin\admin\app\model\UserProfile;

class UserFansService
{
    public static function followers($page, $length = 10, $userId = null)
    {
        $userId = is_null($userId) ? get_user_id() : $userId;

        $offset = ($page - 1) * $length;

        $query = UserFollowing::where('following_user_id', $userId);

        $totalCount = (clone $query)->count();
        $list = $query->offset($offset)->limit($length)->get()->toArray();

        $userIds = array_column($list, 'user_id');
        $userProfiles = UserProfile::select(['user_id', 'nickname', 'avatar', 'fans_count', 'desc', 'no'])->whereIn('user_id', $userIds)->get()->toArray();

        $followingUsers = UserFollowing::where('user_id', get_user_id())->whereIn('following_user_id', $userIds)->get()->toArray();
        $followingUsers = array_combine(
            array_column($followingUsers, 'following_user_id'),
            array_values($followingUsers)
        );

        foreach ($userProfiles as $key=>$userProfile) {
            $userProfiles[$key]['is_following'] = isset($followingUsers[$userProfile['user_id']]);
        }

        return Page::wrap($totalCount, $page, $length, $userProfiles);
    }
}